/*OWmq6Ugo6jPE4W7xoi1UXrKBmw0UE0xLJP33RZKKL52cOviNT1XEDtpmc0kMviyi*/
import {ajax, base, promptBox} from 'nc-lightapp-front';
import constants from '../../constants';
import {setStatus} from "./headButtonClick";
import {updateDeptRefLevel} from './refFilter';
import {getPkTransitype, depmethodUtils} from '../../utils';
let {checkDepmethod} = depmethodUtils;

import ampub from 'ampub';
import fa from 'fa';

const {utils} = ampub;
const {fa_components, fa_utils} = fa;

const {showMessage} = utils.msgUtils;
const {getMultiLangByID} = utils.multiLangUtils;

const {getAccbooksAndPeriods} = fa_components.AccbookAndPeriod;
const {referLinkageClear} = fa_components.ReferLinkage;
const metaUtil = fa_utils.metaUtil;

import {updateDeptmethodItem, updateAssetGroupItem} from './utils';

const {NCMessage} = base;

const assetAllArea = constants.AREA.CARD.ASSET_ALL;
const basicInfoForm = constants.AREA.CARD.BASIC_INFO_AREA;
const financeForm = constants.AREA.CARD.FINANCE_AREA;
const usedept_tab = constants.AREA.CARD.USEDEPT_TAB;
const subequip_tab = constants.AREA.CARD.SUBEQUIP_TAB;
const ReferLinkageClearConfig = constants.ReferLinkageClearConfig;

/**
 * 表头的编辑后事件处理
 *
 * @param props
 * @param moduleId
 * @param field
 * @param newValue
 * @param oldValue
 * @param record
 * @param fromAccbookChange 是否账簿切换
 * @returns {undefined}
 */

export default function afterEvent(props, moduleId, field, newValue, oldValue, record, formValue, fromAccbookChange = false) {
    const that = this;
    //联动处理
    referLinkageClear(this.props, field, ReferLinkageClearConfig, 'form', moduleId);

    //不需要关联处理的字段不需要发请求到后台， 包括自定义项
    if (constants.FIELDS.NORELATION_FIELD.includes(field) || field.startsWith(constants.FIELDS.DEF_FIELD)) {
        return;
    }

    if (field === 'pk_org' || field === 'pk_org_v') {
        orgAfterEdit(that, props, moduleId, field, newValue, oldValue)
    } else {
        eventHandler.call(that, props, moduleId, field, newValue, oldValue, record, formValue, fromAccbookChange)
    }
}

//执行编辑后事件
function eventHandler(props, moduleId, field, newValue, oldValue, record, formValue, fromAccbookChange = false) {
    let that = this;
    let param = {
        isCategoryChange: false, //只是在编辑后使用
        field,
        hisvo_size: that.state.accbooks ? that.state.accbooks.length : 0,
    };

    let {currentPkaccbook, pageCode} = this.state;
    let newasset_flag = this.props.pageConfig.newasset_flag;

    if (field === 'pk_category') {
        //that.editCategoryWhenUpdate = true;
        param.isCategoryChange = true;
        let isContinue = true;//是否继续执行后续操作
        if (!newValue || !newValue.value) {//新值为空
            that.setState({
                financeShowFlag: false,
                accbooks: [],
                currentPkaccbook: ''
            });
            isContinue = false;
        } else if (!oldValue && !oldValue.value) { //新值不为空、旧值为空

        } else if (newValue.value !== oldValue.value) {//新旧值不同
            //param.isCategoryChange = true;
            //如果是类别切换， 则当前选中的账簿设置为空
            // currentPkaccbook = "";
        }

        if (!isContinue) {
            return;
        }
    }

    //使用权的编辑后，清空多使用部门页签数据
    if (field === 'pk_equiporg') {
        props.cardTable.setTableData(usedept_tab, {rows: []});
    }

    if(field === 'business_date') {
        if(!newValue || !newValue.value) {
            currentPkaccbook = "";
            that.setState({
                financeShowFlag: false,
                accbooks: [],
                currentPkaccbook: ''
            });
        }
    }

    //如果当前编辑的不是[资产类别、财务组织]，且资产类别字段为空，则不发送后台请求(关联项的处理是在平台的编辑后处理)
    //之所以这样做是由于类别为空后，后台取账簿数据时会出现错误  @zhangypm 2018-12-12
    let pk_category = props.form.getFormItemsValue(basicInfoForm, 'pk_category').value;
    if (!['pk_category', 'pk_org', 'pk_org_v'].includes(field) && !pk_category) {
        return;
    }

    let assetData = undefined;
    if (currentPkaccbook) {//在有账簿的情况下
        //组装用于提交到后台的数据
        this.syncDataForCommit();

        assetData = Object.values(this.assetDataMap);

    } else {//currentPkaccbook 为空时， assetDataMap 还没有值，需要从界面上取值
        assetData = props.form.getAllFormValue(basicInfoForm);
        assetData = [assetData.rows[0]];
    }

    const {pageConfig} = this.props;

    let pk_transitype = getPkTransitype.call(this, this.curr_transiType);
    if(!pk_transitype) {
        showMessage(props, {color: 'danger', content: '交易类型初始化失败，请关闭页签后重试！'});
        return;
    }
    let userJson = {
        nodecode: pageConfig.nodecode,
        current_accbook: currentPkaccbook,
        fromAccbookChange: fromAccbookChange,
        transi_type: pageCode,
        pk_transitype,
        newasset_flag,
        bill_source: 'handin',
    };

    let newValueObj = newValue ? {value: newValue.value, display: newValue.display} : {};
    let oldValueObj = oldValue ? {value: oldValue.value, display: oldValue.display} : {};

    let data = {
        attrcode: field,
        newValue: newValueObj,
        oldValue: oldValueObj,
        customValue: userJson,
        grid: {
            pageid: pageCode,
            model: {
                areacode: assetAllArea,
                areaType: 'table',
                rows: assetData
            },
        }
    };

    ajax({
        url: constants.URL.headafteredit,
        data,
        async: false,
        success: (res) => {
            let {success, data} = res;
            if (success) {
                if (field === 'pk_org' || field === 'pk_org_v') {
                    orgAfterEventBackHandler.call(that, data);
                } else {
                    afterEventBackHandler.call(that, data, param);
                }
            }
        },
        error: (err) => {
            //清空当前字段值
            let emptyVal = {diplay: '', value: '', scale: (oldValue && oldValue.scale) ? oldValue.scale : -1};
            props.form.setFormItemsValue(moduleId, {[field]: emptyVal});

            showMessage(props, {color: 'danger', content: err.message});
            if(field === 'business_date') {
                that.setState({
                    financeShowFlag: false,
                    accbooks: [],
                    currentPkaccbook: ''
                });
            }
        }
    });

    //使用部门处理
    if (field === constants.FIELDS.USEDEP_FLAG) {
        usedeptChangeHandler.call(that, newValue.value);
    }

}

/**
 * 财务组织编辑后事件
 */
function orgAfterEventBackHandler(data) {
    let assetData = data['toUIObject']['heads'][0][assetAllArea];

    this.props.form.setAllFormValue({
        [basicInfoForm]: assetData
    });

    let paramVO = data['paramVO'];
    let {is_allow_dept_midlev,
        depmethodFormulaFieldMap,
        depmethods,
        org_digit,
        isHeadAssetFinanceorg} = paramVO;

    this.depmethodFormulaFieldMap = depmethodFormulaFieldMap; //折旧方法公式字段
    this.depmethods = depmethods;//折旧方法列表
    
    //更新部门是否能够选择非末级
    updateDeptRefLevel(this, is_allow_dept_midlev);

    //更新【资产组】参照
    updateAssetGroupItem(this.props, !isHeadAssetFinanceorg);

    // 设置附属设备页签的精度，新增的时候没有编辑后事件，所以在这里设置一下
    this.props.cardTable.setColScale([{areacode: subequip_tab, fieldcode: 'originvalue', scale: org_digit}]);


    const pk_org = this.getHeadAttributeValue(data['toUIObject'], 'pk_org');
    getMinUnclosePeriod(pk_org);
}

/**
 * 编辑后事件返回处理（除了 财务组织字段 ）
 */
function afterEventBackHandler(data, param) {

    //后台对当前账簿进行了处理，如果前台已经有选中的账簿，则后台就返回该账簿为当前账簿；
    //如果前台还未选中账簿，则后台设置业务账簿为当前选中账簿
    let {
        fieldsCantEdit,
        current_accbook,
        business_accbook,
        otherUserData,
        toUIObject: {
            heads,
            bodysMap
        },
    } = data;

    this.business_accbook = business_accbook;

    if(param.field === "business_date") {
        businessDateAfterEdit(this, heads, param);
    }

    //更新界面上的数据
    updateValue.call(this, data, param);
    
    //更新业务参数设置
    updateParam.call(this, data, param);

    setStatus.call(this, this.props);
    otherRelativeAfterEdit(this, data, param);

    //修改字段的可编辑性
    //changeFieldEditable.call(this, fieldsCantEdit);
}

//更新数据
function updateValue(data, param) {
    let that = this;
    let {
        current_accbook,
        business_accbook,
        toUIObject: {
            heads,
            bodysMap
        },
    } = data;

    let assetAllData = [];
    if (heads) {
        heads.forEach((head) => {
            if (head[assetAllArea] && head[assetAllArea].rows && head[assetAllArea].rows.length > 0) {
                assetAllData = assetAllData.concat(head[assetAllArea].rows);
            }
        });
    }

    if (current_accbook) {//返回的数据中存在账簿数据
        //解析返回的 assetvo 数据
        let rows = assetAllData;
        let assetDataMap = {};
        let accbooks = [];
        for (let row of rows) {
            const pk_accbook = row['values']['pk_accbook'].value;
            const accbookName = row['values']['pk_accbook'].display;
            //使用月限
            let naturemonthDisplay = this.convertNatureMonthDisplay(row['values']['naturemonth'].value);
            if (naturemonthDisplay) {
                row['values']['naturemonth_display'] = naturemonthDisplay;
            }

            //折旧方法 是否停用 判断处理，如果折旧方法已经停用，则清空该字段
            row['values']['pk_depmethod'] = checkDepmethod(row['values']['pk_depmethod'], this.depmethods);

            accbooks.push({pk_accbook, accbookName});
            assetDataMap[pk_accbook] = row;
        }

        this.assetDataMap = assetDataMap;

        let pkaccbook = current_accbook; //需要展示数据的账簿

        //资产类别变化 或者 当前还未选中账簿
        if (param.isCategoryChange || !this.state.currentPkaccbook) {
            //给账簿排序，业务账簿放在前面
            let accbooksNew = [];
            accbooksNew = accbooks.filter((accbookObj) => {
                return accbookObj['pk_accbook'] === business_accbook;
            });
            accbooksNew = accbooksNew.concat(accbooks.filter((accbookObj) => {
                return accbookObj['pk_accbook'] !== business_accbook;
            }));
            this.setState({
                accbooks: accbooksNew,
                currentPkaccbook: current_accbook, //前台使用后台返回的当前账簿
            });
        }

        //设置基本区域form的值
        this.basicInfoData = assetDataMap[pkaccbook];
        const basicInfoData4Form = this.getBasicInfoData4Form();
        // 设置财务区的值
        const accbookData4Form = this.getAccbookDataByPkaccbook4Form(pkaccbook);

        //更新form数据
        let updateFormFunc = () => {
            let formValueObj = {};
            if (basicInfoData4Form) {
                formValueObj[basicInfoForm] = basicInfoData4Form;
            }
            if (accbookData4Form && that.state.financeShowFlag) {
                formValueObj[financeForm] = accbookData4Form;
            }

            that.props.form.setAllFormValue(formValueObj);
            //更新折旧方法相关字段的item 属性
            updateDeptmethodItem.call(that, this.props, accbookData4Form);
        };

        //财务区域未展开，展开财务区
        if (param.field === 'pk_category' && !this.state.financeShowFlag) {
            this.setState({
                financeShowFlag: true
            }, () => {
                updateFormFunc();
            });
        } else {
            updateFormFunc();
        }

    } else {
        //返回的数据中没有账簿数据，只更新基本区域form数据
        this.props.form.setAllFormValue({[basicInfoForm]: {rows: assetAllData}});
    }
}


//建卡日期编辑后
function businessDateAfterEdit(that, newDataHeads, param) {
   let hisvos_length_old = param.hisvo_size ;
    let pk_accbookSet_new = new Set();
    let assetAllData = [];
    if (newDataHeads) {
        newDataHeads.forEach((head) => {
            if (head[assetAllArea] && head[assetAllArea].rows && head[assetAllArea].rows.length > 0) {
                assetAllData = assetAllData.concat(head[assetAllArea].rows);
            }
        });
    }
    assetAllData.map((head)=>{
        head.values.pk_accbook.value && pk_accbookSet_new.add(head.values.pk_accbook.value);
    });
    let hisvos_length_new = pk_accbookSet_new.size;
    //本次编辑与上次编辑相比 有无变化 （账簿个数的变化认为是类别变化）
    // see nc.ui.fa.asset.event.AssetEventHandler.handleHeadAfterEditEvent()
    param.isCategoryChange = hisvos_length_old !== hisvos_length_new;
}

//由当前编辑字段引起的其他关联字段的编辑后处理
function otherRelativeAfterEdit(that, data, param) {
    let {otherUserData} = data;
    if(otherUserData) {
        let {relativeData} = otherUserData;
        //净残值率反算值
        let salvageReverse = relativeData && relativeData.salvageReverse;
        if(salvageReverse) {
            that.props.modal.show(constants.MODAL_ID.ConfirmModal, {
                title: getMultiLangByID('201201504A-000053')/* 国际化：'提示'*/,
                content:  getMultiLangByID('201201504A-000054') /* 国际化：净残值超出参数设置中（原值*净残值率）允许的最大误差；是否反算净残值率？*/,
                beSureBtnClick: () => {
                    //更新净残值率
                    metaUtil.updateFormItemValue(that.props, financeForm, "salvagerate", salvageReverse);
                },
                //取消
                cancelBtnClick: () => {
                    metaUtil.clearFormItemValue(that.props, financeForm, "salvage");
                }
            });
        }
    }
}

//改变字段的可编辑性(废弃)
function changeFieldEditable(fields) {
    this.props.resMetaAfterPkorgEdit();
    let obj = {};
    fields.forEach((f) => {
        obj[f] = false;
    });
    this.props.form.setFormItemsDisabled(basicInfoForm, obj);
}

//更新参数设置：如FA10,账簿参数等
function updateParam(data, param) {
    if (param.field === 'pk_category') {//类别编辑后，更新FA10
        let {fa10param, accbookCurrency} = data['paramVO'];
        this.fa10param = fa10param;
        this.accbookCurrency = accbookCurrency;
    }

}


//是否多使用部门切换处理
function usedeptChangeHandler(usedept_flag) {
    if (usedept_flag) { //多使用部门
        //清空 使用部门 字段的数据
        this.props.form.setFormItemsValue(basicInfoForm, {[constants.FIELDS.PK_USEDEPT]: {value: '', display: null}});

        // 设置 使用部门 可空
        let obj = {
            [constants.FIELDS.PK_USEDEPT]: false
        };
        this.props.form.setFormItemsRequired(basicInfoForm, obj);

        // 设置 使用部门 不能编辑
        obj = {
            [constants.FIELDS.PK_USEDEPT]: true
        };
        this.props.form.setFormItemsDisabled(basicInfoForm, obj);

        // 设置 多使用部门页签 可以编辑
        this.props.cardTable.setStatus(usedept_tab, constants.UISTATE.EDIT);
        // 多使用部门页签上的按钮可以使用
        let btns = Object.values(constants.CARD_BTNS.TABLE_HEAD.USEDEPT_TAB);
        this.props.button.setButtonVisible(btns, true);

        const status = this.props.getUrlParam('status');
        if ([constants.UISTATE.ADD, constants.UISTATE.EDIT].includes(status)) {
            // 增一行。
            this.props.cardTable.addRow(usedept_tab);
        }

    } else {//单使用部门
        //设置使用部门字段可以编辑
        let obj = {
            [constants.FIELDS.PK_USEDEPT]: false
        };

        this.props.form.setFormItemsDisabled(basicInfoForm, obj);
        // 表头使用部门默认是否可空
        let defaultNotNull = this.state.usedeptIsNotNull;
        obj = {
            [constants.FIELDS.PK_USEDEPT]: defaultNotNull
        };
        this.props.form.setFormItemsRequired(basicInfoForm, obj);

        // 设置表体页签不能编辑
        // 多使用部门页签上的按钮不可以使用
        let btns = Object.values(constants.CARD_BTNS.TABLE_HEAD.USEDEPT_TAB);
        this.props.button.setButtonVisible(btns, false);

        // 把表体多使用部门数据清空
        this.props.cardTable.setTableData(usedept_tab, {rows: []});
        this.props.cardTable.setStatus(usedept_tab, constants.UISTATE.BROWSE);

    }

}


//获取选择组织所有账簿的最小未结帐月，并给出提示
function getMinUnclosePeriod(pk_org) {
    getAccbooksAndPeriods(pk_org, (res) => {
        let {success, data} = res;
        if (success && data && data.length) {
            //主账簿排在前面
            data.sort((a1, a2) => {
                if (a1.isMainbook && !a2.isMainbook) {
                    return 1
                } else if (!a1.isMainbook && a2.isMainbook) {
                    return -1;
                } else {
                    return 0;
                }

            });

            setTimeout(() => {
                NCMessage.create({
                    content: <div>{data.map((a1) => {
                        let {accbookName, minUnClosebookPeriod: {accyear, period}} = a1;
                        return <div><span>{accbookName} {getMultiLangByID('201201504A-000009', {
                            accyear,
                            period
                        })}</span><br/></div>
                    })}</div>,
                    position: 'top',
                    color: 'success',
                    fieldid: 'minUnClosePeriod',
                    duration: 3600
                });
            }, 100);
        }
    });
}

//组织字段的编辑处理
function orgAfterEdit(that, props, moduleId, field, newValue, oldValue) {
    let isContinue = true;//是否继续执行后续操作

    if (oldValue && oldValue.value && (!newValue || (oldValue.value !== newValue.value))) {//组织切换(包括置空)

        //弹出组织切换对话框
        let modalConfig = {
            color: 'warning',
            title: getMultiLangByID('orgChange-000001') /* 国际化处理: 确认修改*/,
            content: getMultiLangByID('orgChange-000000') /* 国际化处理: 是否修改组织，这样会清空您录入的信息? */,
            closeByClickBackDrop: false, //点击遮罩不关闭提示框
            //点击确定按钮事件
            beSureBtnClick: () => {
                if (newValue && newValue.value) {
                    orgChangeHandler(that);
                    eventHandler.call(that, props, moduleId, field, newValue, oldValue, null, null);
                    isContinue = true;
                } else {
                    emptyOrgHandler(that);
                    isContinue = false;
                }

                if (isContinue) {
                    // console.log('------ 调用处于3   resMetaAfterPkorgEdit');
                    that.props.resMetaAfterPkorgEdit();
                } else {
                    // console.log('------ 调用处于2   initMetaByPkorg');
                    that.props.initMetaByPkorg('pk_org');
                }
            },
            //取消按钮事件-恢复原来的值
            cancelBtnClick: () => {
                props.form.setFormItemsValue(moduleId, {[field]: oldValue});
                let data = {
                    type: 'form',
                    areaCode: moduleId,
                    key: field,
                    value: oldValue,
                    callback: () => {
                    },
                    changedrows: null,
                    index: null,
                    formMetaCode: moduleId
                };
                props.handleRelationItems(data);
            }
        };

        promptBox(modalConfig);

    } else {//新增的
        eventHandler.call(that, props, moduleId, field, newValue, oldValue, null, null);
        // console.log('------ 调用处于4   resMetaAfterPkorgEdit');
        that.props.resMetaAfterPkorgEdit();
    }
}


//组织清空处理
function emptyOrgHandler(that) {
    that.resetOnAdd();
    //清除最小未结账月消息
    NCMessage.destroy();
}


//组织切换
function orgChangeHandler(that) {
    //删除账簿数据
    that.setState({
        financeShowFlag: false,
        accbooks: [],
        currentPkaccbook: ''
    });

    //清空资产类别
    that.props.form.setFormItemsValue(basicInfoForm, {pk_category: {value: '', display: ''}});

    //清除最小未结账月消息
    NCMessage.destroy();
}


function natureMonthAfterEvent(props, moduleId, field, newValue, oldValue, record) {
    if (field === 'naturemonth') {
        try {
            let natureMonth = parseInt(newValue.value);
            let naturemonthDisplag = this.convertNatureMonthDisplay(natureMonth);
            if (naturemonthDisplag) {
                props.form.setFormItemsValue(financeForm, {
                    'naturemonth_display': naturemonthDisplag
                });
            }
        } catch (e) {
            /*国际化处理：【使用月限】必须为正整数*/
            showMessage(props, {content: getMultiLangByID('201201504A-000007'), color: 'warning'});
            return false;
        }
    }
    return true;
}
/*OWmq6Ugo6jPE4W7xoi1UXrKBmw0UE0xLJP33RZKKL52cOviNT1XEDtpmc0kMviyi*/